<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../css/issue.css">
    <title>发布文档</title>
  </head>
  <body>
    <div class="header">
      <a class="back" onclick="back()"></a>
      <h3>发布文档</h3>
    </div>
    <div class="body">
      <div class="btn">
        <input style="display:none" type="file" name="file" id="file" value="" accept="image/*" multiple="multiple"><button  type="button" name="button"  onclick="imgOpen()" >添加图片</button>
        <button type="button" name="button"  onclick="show()" >选择分类</button>
      </div>
      <div>
          <span id="classifyShow" style="margin-left:6%">当前未选择分类</span>
      </div>
      <div id="insertImg"></div>
      <div class="titleInput">
        <input type="text" id="title" placeholder="在这里输入标题">
      </div>
      <div class="contentInput">
        <textarea id="content" rows="20" cols="60" placeholder="在这里输入内容"></textarea>
      </div>
      <div class="btn">
        <button class="save" type="button" name="button"  onclick="save()">发布内容</button>
      </div>
    </div>
  </body>
  <script type="text/javascript" src="../../script/api.js"></script>
  <script type="text/javascript" src="../../script/jquery-3.2.1.min.js"></script>
  <script type="text/javascript" src="../../script/main.js"></script>
  <script type="text/javascript">
  var UIMultiSelector;
  var classify = [];  //存放类别的数组
  var index = -1;  //选择类别的索引
  var text = "";
  var aid=$api.getStorage("aid");
  var imageList=[];


apiready = function(){
   init();
   UIMultiSelector = api.require('UIMultiSelector');
     function init(){
         var Url='/api/pa-project-types';
         var functionRet=function(ret){
           for (var i = 0; i < ret.length; i++){
             classify.push({
               text: ret[i].name,
               status: 'normal',
               index: i
               });
               console.log(i);
             }
           }
        var functionErr=function(err){
               return false;
        }
          get(Url,functionRet,functionErr);
     }
}
//返回上一页
function back(){
  api.historyBack({
      frameName: 'detail'
      }, function(ret, err) {
      if (!ret.status) {
         api.closeWin();
      }
      });
}
   //点击添加图片
function imgOpen(){
     $("#file").click();
  }
   //点击提交按钮
function save(){
  if($("#insertImg").html()==""){
    createMsg();
   }
   else{
     if(($("#title").val()!="")&&($("#content textarea").val()!="")){
       createOss();
     }else{
       toast("标题和内容不能为空！","middle");
     }
   }
}
//没图片的上传
function createMsg(){
  var title = $("#title").val();
  var content = $("#content").val();
  //判断标题是否为空
  if (title.replace(/(^s*)|(s*$)/g, "").length ==0){
    toast("标题不能为空！","middle");
    return false;
  }
  //判断内容是否为空
  if (content.replace(/(^s*)|(s*$)/g, "").length ==0){
    toast("内容不能为空！","middle");
    return false;
  }
  if (index < 0){
    toast("未选择分类！","middle");
    return false;
  }
  var Url='/api/public-msgs';
  var data={
          "content": content,
          "imageList": ["'"+imageList+"'"],
          "title": title,
          "type": index,
          "aid": aid
      }
      var functionRet=function(ret1){
        api.hideProgress();

        var jsfun = 'reloadHtml();';
        api.execScript({
            name: 'root',
            frameName: 'frame2',
            script: jsfun
        });
        //关闭本页面
        api.closeWin({
            name: 'issue'
        });
      }
      var functionErr=function(err1){
        console.log(JSON.stringify(err1))
      }
      show_post(Url,data,functionRet,functionErr);
}
//有图片的上传
function createOss(){
  api.showProgress({
    title: '发布中...',
    text: '发布中，请稍后...',
    modal: false
  });
  var url='/api/oss/benyun-test-oss/postPolicy?dir=hsj/';
  var functionRet=function(ret){
    accessid = ret.accessid;
    signature = ret.signature;
    host =ret.host;
    dir =ret.dir;
    expire =ret.expire;
    policy =ret.policy;
    filesName=[];
    //组装发送数据
    for(i=0;i<$("#file")[0].files.length;i++){
      var request = new FormData();
      filesName[i]=new Date().getTime()+'.jpg';
      request.append("OSSAccessKeyId",accessid);//Bucket 拥有者的Access Key Id。
      request.append("policy",policy);//policy规定了请求的表单域的合法性
      request.append("signature",signature);//根据Access Key Secret和policy计算的签名信息，OSS验证该签名信息从而验证该Post请求的合法性
      //---以上都是阿里的认证策略
      request.append("key",'hsj/'+filesName[i]);//文件名字，可设置路径
      request.append("success_action_status",'200');// 让服务端返回200,不然，默认会返回204
      request.append('file', $("#file")[0].files[i]);//需要上传的文件 file
      $.ajax({
              url : host,  //上传阿里地址
              data : request,
              processData: false,//默认true，设置为 false，不需要进行序列化处理
              cache: false,//设置为false将不会从浏览器缓存中加载请求信息
              async: false,//发送同步请求
              contentType: false,//避免服务器不能正常解析文件---------具体的可以查下这些参数的含义
         　　 type : 'post',
          　　success : function(callbackBody, request) { //callbackHost：success,request中就是 回调的一些信息，包括状态码什么的
                imageList.push('benyun-test-oss.oss-cn-shenzhen.aliyuncs.com/hsj/'+filesName[i]);
                console.log(imageList[i])
          },
          error : function(returndata) {
              alert(JSON.stringify(returndata));
          }
      });
    }
    createMsg();
  }
  var functionErr=function(err){

  }
  get(url,functionRet,functionErr);
 }

$("#file").change(function(){
    $("#insertImg").empty();
    var file=$(this)[0].files;
    var url;
    for(i=0;i<file.length;i++){
      if (window.createObjcectURL != undefined) {
              url = window.createOjcectURL(file[i]);
          } else if (window.URL != undefined) {
              url = window.URL.createObjectURL(file[i]);
          } else if (window.webkitURL != undefined) {
              url = window.webkitURL.createObjectURL(file[i]);
          }
        $("#insertImg").append("<img src='" + url + "' style='width:100%;'/>")
    };
})
   //将列表显示出来
   function show(){
     UIMultiSelector.open({
         rect: {
             h: 244
         },
         text: {
             title: '选择分类',
             leftBtn: '返回',
             rightBtn: '完成',
         },
         max: 0,
         singleSelection: true,
         styles: {
             mask: 'rgba(0,0,0,0.3)',
             title: {
                 bg: 'rgb(255,255,255)',
                 color: 'rgb(0,0,0)',
                 size: 16,
                 h: 44
             },
             leftButton: {
                 bg: 'rgb(255,245,225)',
                 w: 80,
                 h: 35,
                 marginT: 5,
                 marginL: 8,
                 color: 'rgb(0,0,0)',
                 size: 14
             },
             rightButton: {
                 bg: 'rgb(255,251,240)',
                 w: 80,
                 h: 35,
                 marginT: 5,
                 marginR: 8,
                 color: 'rgb(0,0,0)',
                 size: 14
             },
             item: {
                 h: 35,
                 bg: 'rgb(255,255,255)',
                 bgActive: '#33FFFF',
                 bgHighlight: '#33FFFF',
                 color: 'rgb(0,0,0)',
                 active: '#FFF',
                 highlight: 'rgb(0,0,0)',
                 size: 14,
                 lineColor: 'rgb(0,0,0)',
                 textAlign: 'center'
             },
             icon: {
                   marginT: 11,
                   marginH: 0,
                   align: 'left'
               }
         },
         animation: true,
         items: classify,
     }, function(ret, err) {
         if (ret) {
             if(ret.eventType == 'clickMask'){
               UIMultiSelector.hide();
             }
             if(ret.eventType == 'clickLeft'){
                UIMultiSelector.hide();
             }
             if(ret.eventType == 'clickItem'){
               var json = JSON.stringify(ret);
               text = json.split('text":"')[1].split('"')[0];
               index = json.split('index":')[1].split('}')[0];
             }
             if(ret.eventType == 'clickRight'){
                 if(index >= 0){
                   $("#classifyShow").html("当前已选择"+text);
                 }
                UIMultiSelector.hide();
             }

         } else {
             alert(JSON.stringify(err));
         }
     });
  }

  </script>
</html>
